import { ref, computed } from 'vue'
import { getUserMessageUnreadCountApi } from '#/api/personal'

// 全局状态，确保所有地方使用同一个实例
const unreadCount = ref<number>(0)
const loading = ref<boolean>(false)
const lastUpdateTime = ref<number>(0)

export const useMessage = () => {
  
  // 计算属性：显示的徽标数量（最大99）
  const badgeCount = computed(() => {
    if (unreadCount.value === 0) return 0
    return Math.min(unreadCount.value, 99)
  })

  // 计算属性：是否显示红点
  const showDot = computed(() => unreadCount.value > 0)

  /**
   * 获取未读消息数量
   */
  const fetchUnreadCount = async () => {
    try {
      loading.value = true
      const count = await getUserMessageUnreadCountApi()
      unreadCount.value = count
      lastUpdateTime.value = Date.now()
      return count
    } catch (error) {
      console.error('获取未读消息数量失败:', error)
      return 0
    } finally {
      loading.value = false
    }
  }

  /**
   * 设置未读消息数量
   */
  const setUnreadCount = (count: number) => {
    unreadCount.value = count
    lastUpdateTime.value = Date.now()
  }

  /**
   * 增加未读消息数量
   */
  const incrementUnreadCount = (increment: number = 1) => {
    unreadCount.value += increment
    lastUpdateTime.value = Date.now()
  }



  /**
   * 清空未读消息数量
   */
  const clearUnreadCount = () => {
    unreadCount.value = 0
    lastUpdateTime.value = Date.now()
  }

  /**
   * 重置状态
   */
  const resetMessage = () => {
    unreadCount.value = 0
    loading.value = false
    lastUpdateTime.value = 0
  }

  return {
    // 状态
    unreadCount,
    loading,
    lastUpdateTime,

    // 计算属性
    badgeCount,
    showDot,

    // 方法
    fetchUnreadCount,
    setUnreadCount,
    incrementUnreadCount,
    clearUnreadCount,
    resetMessage,
  }
} 
